/**
 *
 */
package com.nishop.service;

import com.nishop.api.IGoodsAttrsService;
import com.nishop.api.common.NiShopConstant;
import com.nishop.api.entity.Category;
import com.nishop.api.entity.CategoryExample;
import com.nishop.api.form.BaseRequestForm;
import com.nishop.api.util.Identity;
import com.nishop.service.dao.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 李建成
 *
 */
@Service
public class GoodsAttrsServiceImpl implements IGoodsAttrsService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> queryList(BaseRequestForm requestForm) {
        return tranferCatedgory(NiShopConstant.ROOT);
    }


    /**
     * 递归
     * @param pid
     * @return
     */
    List<Category> tranferCatedgory(String pid) {
        CategoryExample base = getCategoryExample();
        base.createCriteria().andParentIdEqualTo(pid);
        List<Category> categories = categoryMapper.selectByExample(base);
        if (categories.size() > 0) {
            categories.forEach(e -> e.setChildren(tranferCatedgory(e.getId())));
        }
        return categories;
    }

    private CategoryExample getCategoryExample() {
        return new CategoryExample();
    }


    @Override
    public long queryCount() {
        CategoryExample e = getCategoryExample();
        e.createCriteria().andParentIdEqualTo(NiShopConstant.ROOT);
        return categoryMapper.countByExample(e);
    }


    @Override
    public Boolean edit(Category category) {
        return categoryMapper.updateByPrimaryKeySelective(category) > 0;
    }

    @Override
    public Boolean add(Category category) {
        category.setId(Identity.uuidWithoutHyphen());
        return categoryMapper.insert(category) > 0;
    }

    @Override
    public Boolean del(Category category) {

        String id = category.getId();

        if (Objects.isNull(id)) {
            return false;
        }

        return categoryMapper.deleteByPrimaryKey(id) > 0;
    }
}
